#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>

#include "global.h"
#include "memorypool.h"
#include "csocket.h"


pSConnection CSocket::getConnection(int sockfd)
{
    pSConnection conn = m_pHeadFreeConnections; //指向空闲连接链表的头部
    if (conn == nullptr)
    {
        LOGSTDERR(errno, "CSocket::getConnection() conn nullptr");
        return nullptr;
    }

    m_pHeadFreeConnections = conn->next; //表头往后移动一个元素
    m_freeConnectionNum -= 1;

    uintptr_t instance = conn->instance; //有些有用的变量提取出来备用
    uint64_t curSeq = conn->iCurSeq;

    memset(conn, 0, sizeof(SConnection)); //清空这个连接
    conn->fd = sockfd;
    conn->curStat = pktStatus::HEADINIT;
    conn->pRecvBuf = conn->dataHeadInfo;
    conn->recvLen = sizeof(PKT_HEADER);
    conn->ifNew = false;

    conn->instance = !instance;
    conn->iCurSeq = curSeq + 1;

    return conn;
}


void CSocket::releaseConnection(pSConnection c)
{
    if (c->ifNew)
    {
        CMemory::GetInstance()->FreeMemory(c->pNewMem);
        c->pNewMem = nullptr;
        c->ifNew = false;
    }

    c->next = m_pHeadFreeConnections;
    ++c->iCurSeq;
    m_pHeadFreeConnections = c;
    ++m_freeConnectionNum;
    return ;
}


void CSocket::closeConnection(pSConnection c)
{
    if (close(c->fd) == -1)
    {
        LOGSTDERR(errno, "CSocket::closeConnection() close() error");
    }
    c->fd = -1;
    releaseConnection(c);
    return ;
}
